package com.idea.relax.redis.toolkit;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 沉香
 * @date: 2023/2/14
 * @description: redis扩展脚本的加载器
 */
public class RedisExtScriptsLoader {


    private static final Map<EXT_OPS, Script> SCRIPTS_URL = new HashMap<>(16);


    public RedisExtScriptsLoader() {
        SCRIPTS_URL.put(EXT_OPS.HEXMSET, new Script<>("META-INF/scripts/ext/hash_expire_mset.lua", Long.class));
        SCRIPTS_URL.put(EXT_OPS.HEXSET, new Script<>("META-INF/scripts/ext/hash_expire_set.lua", Void.class));
    }

    public Map<EXT_OPS, RedisScript<?>> load() {
        Map<EXT_OPS, RedisScript<?>> scriptMap = new HashMap<>(16);
        SCRIPTS_URL.forEach((k, v) -> {
            DefaultRedisScript<?> redisScript = new DefaultRedisScript<>();
            redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(v.getUrl())));
            redisScript.setResultType(v.getResultType());
            scriptMap.put(k, redisScript);
        });
        return scriptMap;
    }

    enum EXT_OPS {
        HEXMSET,
        HEXSET
    }

    @Getter
    @Setter
    @AllArgsConstructor
    class Script<T> {

        private String url;

        private Class<T> resultType;

    }

}
